<template>
  <div class="dashboard-container" ref="dashboardContainer">
    <!-- 顶部栏与侧边栏将由MainHeader和SideMenu组件提供 -->
    <MainHeader />
    
    <!-- 广告悬浮图标 -->
    <div class="ad-float-icon" @click="toggleAdPopup" :title="t('dashboard.ad.moreServices')">
      <img src="../../images/1.png" :alt="t('brand.name')" class="ad-icon-img">
      <span class="ad-icon-text" v-html="t('dashboard.ad.moreServicesLabel').replace('\\n','<br>')"></span>
    </div>
    
    <!-- 公司其他业务广告弹窗 -->
    <div class="ad-popup" v-if="showAdPopup">
      <div class="ad-content">
        <div class="ad-header">
          <h3>{{ popupTitle || t('dashboard.ad.businessPromotion') }}</h3>
          <div class="ad-close" @click="closeAdPopup">×</div>
        </div>
        <div class="ad-body">
          <div class="ad-image-container">
            <img src="../../images/1.png" :alt="t('brand.name')" class="ad-logo">
          </div>
          <div class="ad-info">
            <h4>{{ popupHeadline || t('dashboard.ad.moreProfessionalServicesTitle') }}</h4>
            <div v-if="popupContentHtml" class="popup-rich-content" v-html="popupContentHtml"></div>
            <template v-else>
              <p>{{ t('dashboard.ad.moreServicesDesc') }}</p>
              <ul>
                <li>{{ t('dashboard.ad.service.crossBorderEcommerce') }}</li>
                <li>{{ t('dashboard.ad.service.overseasMarketingAnalytics') }}</li>
                <li>{{ t('dashboard.ad.service.globalSupplyChain') }}</li>
                <li>{{ t('dashboard.ad.service.internationalBusinessConsulting') }}</li>
              </ul>
            </template>
          </div>
        </div>
        <div class="ad-footer">
          <button class="ad-button primary" @click="learnMoreAboutServices"><Translate keyName="common.learnMore" /></button>
          <button class="ad-button secondary" @click="closeAdPopup"><Translate keyName="common.later" /></button>
        </div>
      </div>
    </div>
    
    <div class="main-container">
      <!-- 左侧导航 -->
      <SideMenu />
      <!-- 主内容区域 -->
      <div class="scrollable-area" ref="scrollableArea">
        <div class="content">
    <!-- 顶部滚动公告 -->
    <div class="marquee-container">
      <div class="marquee-icon">
        <i class="el-icon-bell"></i>
      </div>
      <div class="marquee-content">
        <div class="marquee-text">{{ announcementsText }}</div>
      </div>
    </div>
          <div class="dashboard-layout">
            <!-- 左侧图表区域 -->
          <div class="charts-section">
            <div class="export-search-stats-card">
              <div class="stats-title">{{ t('dashboard.export.search.stats') }}</div>
              <div ref="statsBarChart" class="stats-bar-chart"></div>
            </div>
            
            <div class="search-pie-card">
              <div class="stats-title">{{ t('dashboard.search.count') }}</div>
              <div class="search-counts-chart">
                <div ref="searchPieChart" class="pie-chart"></div>
                <div class="chart-legend">
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #409EFF;"></span>
                    <span class="legend-text">{{ t('tools.smartEmailSearch') }}: {{ searchCounts.intelligentMail }}{{ t('dashboard.items') }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #67C23A;"></span>
                    <span class="legend-text">{{ t('tools.emailLookup') }}: {{ searchCounts.emailReverse }}{{ t('dashboard.items') }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #E6A23C;"></span>
                    <span class="legend-text">{{ t('tools.domainLookup') }}: {{ searchCounts.domainReverse }}{{ t('dashboard.items') }}</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-color" style="background-color: #F56C6C;"></span>
                    <span class="legend-text">{{ t('tools.socialLookup') }}: {{ searchCounts.socialReverse }}{{ t('dashboard.items') }}</span>
                  </div>
                </div>
              </div>
            </div>
              
              <!-- 视频教程卡片 -->
<!--              <div class="video-tutorials-card" id="videoTutorials" ref="videoTutorials">-->
<!--                <div class="stats-title">使用教程</div>-->
<!--                <div class="video-tutorials-grid">-->
<!--                  <div class="tutorial-item" @click="playVideo('enterprise')">-->
<!--                    <div class="tutorial-thumbnail">-->
<!--                      <span class="duration">02:43</span>-->
<!--                      <div class="play-button"></div>-->
<!--                      <img src="@/assets/images/multi-search.png" alt="企业/领英获客教程" class="thumbnail-img" />-->
<!--                    </div>-->
<!--                    <div class="tutorial-title">企业/领英获客教程</div>-->
<!--                    <div class="tutorial-action">点击了解 <i class="el-icon-arrow-right"></i></div>-->
<!--                  </div>-->
<!--                  <div class="tutorial-item" @click="playVideo('canton')">-->
<!--                    <div class="tutorial-thumbnail">-->
<!--                      <span class="duration">02:08</span>-->
<!--                      <div class="play-button"></div>-->
<!--                      <img src="@/assets/images/one-click-send.png" alt="广交会使用教程" class="thumbnail-img" />-->
<!--                    </div>-->
<!--                    <div class="tutorial-title">广交会使用教程</div>-->
<!--                    <div class="tutorial-action">点击了解 <i class="el-icon-arrow-right"></i></div>-->
<!--                  </div>-->
<!--                  <div class="tutorial-item" @click="playVideo('customs')">-->
<!--                    <div class="tutorial-thumbnail">-->
<!--                      <span class="duration">02:35</span>-->
<!--                      <div class="play-button"></div>-->
<!--                      <img src="@/assets/images/realtime-monitoring.png" alt="海关数据使用教程" class="thumbnail-img" />-->
<!--                    </div>-->
<!--                    <div class="tutorial-title">海关数据使用教程</div>-->
<!--                    <div class="tutorial-action">点击了解 <i class="el-icon-arrow-right"></i></div>-->
<!--                  </div>-->
<!--                </div>-->
<!--                <div class="view-all" @click="showAllTutorials">-->
<!--                  查看全部 <i class="el-icon-arrow-down"></i>-->
<!--                </div>-->
<!--              </div>-->
          </div>
            
            <!-- 右侧用户信息卡片 -->
            <div class="user-info-section">
              <div class="user-card">
                <!-- 用户基本信息 -->
                <div class="user-profile">
                  <div class="avatar-container">
                    <div class="avatar">L</div>
                  </div>
                  <div class="user-details">
                    <div class="user-id">
                      <span>{{ userInfo.username || 'LUOBO2880' }}</span>
                      <span class="member-tag" :class="`level-${userInfo.memberLevel}`"><Translate :keyName="getMemberLevelKey(userInfo.memberLevel)" /></span>
                    </div>
                    <div class="account-link">
                      <Translate keyName="user.account" /> <i class="el-icon-arrow-right"></i>
                    </div>
                  </div>
                </div>
                
                <!-- 会员信息 -->
                <div class="membership-info">
                  <div class="membership-text" v-html="t('dashboard.membership.tip')"></div>
                  <el-button type="primary" class="upgrade-btn" @click="handleUpgrade">{{ t('dashboard.membership.upgradeNow') }}</el-button>
                </div>
                
                <!-- 账户余额 -->
                <div class="account-balance">
                  <div class="balance-label">{{ t('dashboard.balance.exportRemaining') }}</div>
                  <div class="balance-info">
                    <span class="balance-amount">{{ userInfo.exportQuotaRemaining || '0' }}</span>
<!--                    <el-button size="small" class="recharge-btn" @click="handleRecharge">充值</el-button>-->
                  </div>
                </div>
                
                <!-- 剩余搜索次数 -->
                <div class="search-remaining">
                  <div class="remaining-label">{{ t('dashboard.balance.searchRemaining') }}</div>
                  <div class="remaining-count">{{ userInfo.remainingSearches || '8' }}</div>
                </div>
              </div>
              
              <!-- VIP广告横幅卡片 -->
              <div class="user-card vip-card">
                <!-- VIP广告横幅 -->
                <div class="vip-banner" @click="handleVipActivation">
                  <img src="@/assets/vip-banner.svg" :alt="t('dashboard.vip.openVIP')" class="vip-banner-img" />
                </div>
              </div>
              
              <!-- 技术顾问卡片 -->
              <div class="user-card advisor-card">
                <!-- 技术顾问 -->
                <div class="tech-support">
                  <div class="support-header">
                    <img src="../../images/1.png" :alt="t('brand.name')" class="advisor-icon" />
                    <div class="support-text">
                      <div class="support-title"><Translate keyName="dashboard.advisor.title" /></div>
                      <div class="support-desc"><Translate keyName="dashboard.advisor.desc" /></div>
                    </div>
                  </div>
                  <div class="qrcode-links-container">
                    <div class="qr-code">
                      <img src="../../images/2.png" :alt="t('dashboard.advisor.qrAlt')" class="qr-code-img" />
                    </div>
                    <div class="support-links">
                      <div class="link-item"><Translate keyName="dashboard.advisor.links.features" /></div>
                      <div class="link-item"><Translate keyName="dashboard.advisor.links.faq" /></div>
                      <div class="link-item"><Translate keyName="dashboard.advisor.links.feedback" /></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { ElConfigProvider, ElMessage } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import enUs from 'element-plus/dist/locale/en.mjs'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import Translate from '@/components/Translate.vue'
import { t, getCurrentLanguage, LANGUAGES, diagnoseTranslationSystem } from '@/utils/i18n'
import { useLanguageStore } from '@/store/language'
import * as echarts from 'echarts'
import { getDashboardStats, getSearchCountStats } from '@/api/dashboard'
import { getUserInfo, getUserBalanceInfo } from '@/api/user'
import { getPublishedAnnouncements } from '@/api/announcements'
import { getEnablePopups } from '@/api/businesspopups'

const languageStore = useLanguageStore()
const router = useRouter()
const dateRange = ref(['2025-03-17', '2025-04-16'])
const dashboardContainer = ref(null)
const scrollableArea = ref(null)
const scrollbar = ref(null)
const scrollThumb = ref(null)
const isPageVisible = ref(true)
const statsBarChart = ref(null)
const searchPieChart = ref(null)
let chartInstance = null
let pieChartInstance = null
let refreshTimer = null
const videoTutorials = ref(null)
const currentVideo = ref(null)
const showVideoModal = ref(false)
const showAdPopup = ref(false)
// 顶部公告文本，默认使用i18n兜底
const announcementsText = ref(t('dashboard.marquee.text'))
// 业务弹窗数据
const popupTitle = ref('')
const popupHeadline = ref('')
const popupContentHtml = ref('')
const popupRedirectUrl = ref('')

// 用户信息
const userInfo = reactive({
  username: '',
  phone: '134****2495',
  balance: '0.00',
  remainingSearches: 8,
  isFree: true,
  exportQuotaRemaining: 0, // 新增导出配额剩余次数
  memberLevel: 0 // 新增会员等级字段
})

// 获取用户信息的函数
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) return
    
    // 获取用户基本信息
    const res = await getUserInfo()
    if (res && res.code === 200 && res.data) {
      // console.log("测试数据",res.data)
      userInfo.username = res.data.username || 'LUOBO2880'
      userInfo.phone = res.data.phone || '134****2495'
      // 其他用户信息更新...
    }

    // 获取用户余额信息
    const balanceRes = await getUserBalanceInfo()
    if (balanceRes && balanceRes.code === 200 && balanceRes.data) {
      userInfo.memberLevel = balanceRes.data.vipLevel || balanceRes.data.vip_level || 0

      // 更新账户余额
      userInfo.balance = balanceRes.data.cashBalance ? balanceRes.data.cashBalance.toFixed(2) : '0.00'
      // 更新剩余搜索次数
      userInfo.remainingSearches = balanceRes.data.viewRecordsRemaining || 0
      userInfo.exportQuotaRemaining = balanceRes.data.exportQuotaRemaining || 0 // 更新导出配额剩余次数
    }
  } catch (error) {
    ElMessage.error(t('dashboard.load.user.failed'))
  }
}

// 处理升级会员
const handleUpgrade = () => {
  router.push('/personal-center?tab=memberCenter')
}

// 处理充值
const handleRecharge = () => {
  router.push('/recharge')
}

// 处理VIP激活
const handleVipActivation = () => {
  router.push('/personal-center?tab=memberCenter')
}

// 会员等级对应的翻译键
const getMemberLevelKey = (level) => {
  const levelKeyMap = {
    0: 'user.freeVersion',
    1: 'user.basicVip',
    2: 'user.advancedVip',
    3: 'user.premiumVip'
  }
  return levelKeyMap[level] || 'user.freeVersion'
}

// 滚动到视频教程部分
const scrollToVideoTutorial = () => {
  if (videoTutorials.value) {
    videoTutorials.value.scrollIntoView({ behavior: 'smooth' })
  }
}

// 关闭广告弹窗
const closeAdPopup = () => {
  showAdPopup.value = false
}

// 切换广告弹窗显示状态
const toggleAdPopup = () => {
  const nextState = !showAdPopup.value
  showAdPopup.value = nextState
  if (nextState) {
    // 打开时尝试加载最新后端弹窗内容
    loadBusinessPopup()
  }
}

// 了解更多服务
const learnMoreAboutServices = () => {
  const url = popupRedirectUrl.value || 'https://www.example.com/services'
  window.open(url, '_blank')
  closeAdPopup()
}

// 根据当前语言设置选择正确的地区设置
const currentLocale = computed(() => {
  return languageStore.currentLanguage === LANGUAGES.EN ? enUs : zhCn
})

// 滚动条相关
const thumbPosition = ref(0)
const thumbHeight = ref(100)
const isDragging = ref(false)
const startY = ref(0)
const startTop = ref(0)
const scrollRatio = ref(1)

const startScroll = (e) => {
  isDragging.value = true
  startY.value = e.clientY
  startTop.value = thumbPosition.value
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopScroll)
  e.preventDefault()
}

const onDrag = (e) => {
  if (!isDragging.value) return
  
  const deltaY = e.clientY - startY.value
  let newPosition = startTop.value + deltaY
  
  // 限制滑块在滚动条范围内
  const scrollbarHeight = scrollbar.value.clientHeight
  const maxTop = scrollbarHeight - thumbHeight.value
  
  newPosition = Math.max(0, Math.min(newPosition, maxTop))
  thumbPosition.value = newPosition
  
  // 更新内容区域滚动位置
  const scrollableHeight = scrollableArea.value.scrollHeight - scrollableArea.value.clientHeight
  const scrollPosition = (newPosition / maxTop) * scrollableHeight
  scrollableArea.value.scrollTop = scrollPosition
}

const stopScroll = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopScroll)
}

const updateScrollbar = () => {
  if (!scrollableArea.value || !scrollbar.value) return
  
  const scrollbarHeight = scrollbar.value.clientHeight
  const viewportHeight = scrollableArea.value.clientHeight
  const contentHeight = scrollableArea.value.scrollHeight
  
  // 计算滑块高度比例
  const ratio = viewportHeight / contentHeight
  thumbHeight.value = Math.max(30, scrollbarHeight * ratio)
  scrollRatio.value = (scrollbarHeight - thumbHeight.value) / (contentHeight - viewportHeight || 1)
  
  // 更新滑块位置
  thumbPosition.value = scrollableArea.value.scrollTop * scrollRatio.value
}

const onContentScroll = () => {
  if (!isDragging.value && scrollableArea.value) {
    thumbPosition.value = scrollableArea.value.scrollTop * scrollRatio.value
  }
}

const searchCounts = ref({
  intelligentMail: 0,
  emailReverse: 0,
  domainReverse: 0,
  socialReverse: 0
})
async function loadSearchCounts() {
  if (!isPageVisible.value) return
  
  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }
  
  try {
    const response = await getSearchCountStats()
    if (response && response.code === 200 && response.data) {
      const data = response.data
      searchCounts.value.intelligentMail = data.intelligentMailSearchCount || 0
      searchCounts.value.emailReverse = data.emailReverseSearchCount || 0
      searchCounts.value.domainReverse = data.domainReverseSearchCount || 0
      searchCounts.value.socialReverse = data.socialMediaReverseSearchCount || 0
    } else {
      // 清空数据而不是使用本地存储的模拟数据
      searchCounts.value.intelligentMail = 0
      searchCounts.value.emailReverse = 0
      searchCounts.value.domainReverse = 0
      searchCounts.value.socialReverse = 0
    }
    
    // 确保数据加载后更新图表
    nextTick(() => {
      renderSearchPieChart()
    })
  } catch (error) {
    ElMessage.error(t('dashboard.load.search.stats.failed'))
    // 清空数据
    searchCounts.value.intelligentMail = 0
    searchCounts.value.emailReverse = 0
    searchCounts.value.domainReverse = 0
    searchCounts.value.socialReverse = 0
    
    // 确保即使出错也尝试渲染图表
    nextTick(() => {
      renderSearchPieChart()
    })
  }
}

const statsList = ref([
  // { key: 'customs', export: 0, search: 0 }, // 海关数据 - 已注释掉
  { key: 'globalEnterprise', export: 0, search: 0 },
  { key: 'cantonPurchasers', export: 0, search: 0 },
  { key: 'cantonExhibitors', export: 0, search: 0 },
  { key: 'linkedin', export: 0, search: 0 },
  { key: 'facebook', export: 0, search: 0 },
  { key: 'twitter', export: 0, search: 0 },
])

function getLabelTranslationKey(key) {
  const keyMap = {
    // 'customs': 'dashboard.customsData', // 海关数据 - 已注释掉
    'globalEnterprise': 'dashboard.enterprise',
    'cantonPurchasers': 'dashboard.cantonFairBuyers',
    'cantonExhibitors': 'dashboard.cantonFairExhibitors',
    'linkedin': 'nav.linkedin_leads',
    'facebook': 'nav.facebook_leads',
    'twitter': 'nav.twitter_leads'
  }
  return keyMap[key] || key
}

function renderStatsBarChart() {
  if (!statsBarChart.value || !isPageVisible.value) return
  
  try {
    // 确保DOM元素可用
    if (!document.contains(statsBarChart.value)) {
      return
    }
    
    // 如果图表实例不存在或已被销毁，重新创建
    if (!chartInstance) {
      chartInstance = echarts.init(statsBarChart.value)
      window.addEventListener('resize', () => {
        if (chartInstance) chartInstance.resize()
      })
    }
    const option = {
      tooltip: { trigger: 'axis' },
      legend: { data: [t('dashboard.export.count'), t('dashboard.search.count')] },
      grid: { left: 30, right: 30, bottom: 30, top: 40, containLabel: true },
      xAxis: {
        type: 'category',
        data: statsList.value.map(item => t(getLabelTranslationKey(item.key))),
        axisLabel: {
          fontSize: 14,
          interval: 0,
          formatter: function (value) {
            // 如果是中文环境，进行换行处理
            if (value.includes(t('dashboard.enterprise'))) {
              return value.replace(t('dashboard.enterprises'), '\n' + t('dashboard.enterprises'))
            } else if (value.includes(t('dashboard.cantonFairBuyers'))) {
              return value.replace(t('dashboard.fairBuyers'), '\n' + t('dashboard.fairBuyers'))
            } else if (value.includes(t('dashboard.cantonFairExhibitors'))) {
              return value.replace(t('dashboard.fairExhibitors'), '\n' + t('dashboard.fairExhibitors'))
            } else if (value.includes(t('dashboard.leads'))) {
              return value.replace(t('dashboard.leads'), '\n' + t('dashboard.leads'))
            } else {
              return value
            }
          }
        }
      },
      yAxis: { type: 'value', minInterval: 1 },
      series: [
        {
          name: t('dashboard.export.count'),
          type: 'bar',
          data: statsList.value.map(item => item.export),
          itemStyle: { color: '#409eff' },
          barWidth: 22
        },
        {
          name: t('dashboard.search.count'),
          type: 'bar',
          data: statsList.value.map(item => item.search),
          itemStyle: { color: '#faad14' },
          barWidth: 22
        }
      ]
    }
    
    chartInstance.setOption(option)
  } catch (error) {
    // console.error('渲染导出搜索统计图表出错:', error)
  }
}

function renderSearchPieChart() {
  if (!searchPieChart.value || !isPageVisible.value) return
  
  try {
    // 确保DOM元素可用
    if (!document.contains(searchPieChart.value)) {
      return
    }
    
    // 销毁旧的图表实例
    if (pieChartInstance) {
      pieChartInstance.dispose()
      pieChartInstance = null
    }
    pieChartInstance = echarts.init(searchPieChart.value)
    
    // 准备饼图数据
    const pieData = [
      { 
        value: searchCounts.value.intelligentMail, 
        name: t('tools.smartEmailSearch'), 
        itemStyle: { color: '#409EFF' } 
      },
      { 
        value: searchCounts.value.emailReverse, 
        name: t('tools.emailLookup'), 
        itemStyle: { color: '#67C23A' } 
      },
      { 
        value: searchCounts.value.domainReverse, 
        name: t('tools.domainLookup'), 
        itemStyle: { color: '#E6A23C' } 
      },
      { 
        value: searchCounts.value.socialReverse, 
        name: t('tools.socialLookup'), 
        itemStyle: { color: '#F56C6C' } 
      }
    ].filter(item => item.value > 0) // 只显示有数据的项
    
    // 图表配置
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}' + t('dashboard.items') + ' ({d}%)'
      },
      series: [
        {
          name: t('dashboard.search.count'),
          type: 'pie',
          radius: ['40%', '70%'], // 环形图
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: pieData
        }
      ]
    }
    
    // 应用配置
    pieChartInstance.setOption(option)
    // 添加窗口大小变化事件监听器
    window.addEventListener('resize', () => {
      if (pieChartInstance) pieChartInstance.resize()
    })
  } catch (error) {
    // console.error('渲染搜索饼图出错:', error)
  }
}

// 从后端加载导出和搜索统计数据
async function loadExportSearchStats() {
  if (!isPageVisible.value) return
  
  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }
  
  try {
    const response = await getDashboardStats()
    if (response && response.code === 200 && response.data) {
      const data = response.data
      
      // 更新statsList数据
      statsList.value.forEach(item => {
        if (data[item.key]) {
          item.export = data[item.key].exportCount || 0
          item.search = data[item.key].searchCount || 0
        } else {
          // 如果后端没有返回对应数据，设置为0
          item.export = 0
          item.search = 0
        }
      })
    } else {
      // console.error('加载工作台统计数据失败', response)
      // 清空数据而不是使用本地存储的模拟数据
      statsList.value.forEach(item => {
        item.export = 0
        item.search = 0
      })
    }
    
    // 确保数据加载后更新图表
    nextTick(() => {
      renderStatsBarChart()
    })
  } catch (error) {
    // console.error('加载工作台统计数据出错', error)
    ElMessage.error(t('dashboard.load.stats.failed'))
    
    // 清空数据
    statsList.value.forEach(item => {
      item.export = 0
      item.search = 0
    })
    
    // 确保即使出错也尝试渲染图表
    nextTick(() => {
      renderStatsBarChart()
    })
  }
}

// 刷新所有数据和图表
function refreshAllData() {
  if (!isPageVisible.value) return
  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }
  
  Promise.all([
    loadSearchCounts(),
    loadExportSearchStats()
  ]).then(() => {
    // 确保DOM已更新后再渲染图表
    nextTick(() => {
      renderStatsBarChart()
      renderSearchPieChart()
      
      setTimeout(() => {
        if (chartInstance) chartInstance.resize()
        if (pieChartInstance) pieChartInstance.resize()
      }, 200)
    })
  }).catch(error => {
    // console.error('刷新数据出错:', error)
  })
}

// 页面可见性变化处理
function handleVisibilityChange() {
  if (document.hidden) {
    isPageVisible.value = false
  } else {
    isPageVisible.value = true
    refreshAllData()
  }
}

// 初始化定时刷新
function setupRefreshTimer() {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  
  refreshTimer = setInterval(() => {
    if (isPageVisible.value) {
      refreshAllData()
    }
  }, 5 * 60 * 1000)
}

// 从后端加载公告并拼接为滚动文本
async function loadAnnouncements() {
  try {
    const res = await getPublishedAnnouncements({ status: 1, lang: getCurrentLanguage() })
    if (res && res.code === 200 && Array.isArray(res.data) && res.data.length > 0) {
      const contents = res.data
        .map(item => {
          // 支持后端直接返回字符串数组或对象数组
          const raw = typeof item === 'string' ? item : (item?.announcement_content || item?.content || '')
          // 去除可能的HTML标签，仅保留文本内容
          return (raw || '').replace(/<[^>]*>/g, '').trim()
        })
        .filter(Boolean)
      announcementsText.value = contents.length > 0 ? contents.join(' | ') : t('dashboard.marquee.text')
    } else {
      announcementsText.value = t('dashboard.marquee.text')
    }
  } catch (e) {
    // 失败时使用兜底文案
    announcementsText.value = t('dashboard.marquee.text')
  }
}

// 从后端加载业务弹窗内容（顶层定义）
async function loadBusinessPopup() {
  try {
    const res = await getEnablePopups({ status: 1, lang: getCurrentLanguage() })
    // 兼容返回为对象或数组的情况
    const list = Array.isArray(res?.data) ? res.data : (res?.data ? [res.data] : [])
    if (res && res.code === 200 && list.length > 0) {
      const item = list[0]

      // 字段兼容
      popupTitle.value = item.popupTitle || item.title || ''
      popupHeadline.value = item.popupContentTitle || item.headline || ''
      popupContentHtml.value = item.popupContent || item.content || ''
      popupRedirectUrl.value = item.redirectUrl || item.url || ''
    } else {
      popupTitle.value = ''
      popupHeadline.value = ''
      popupContentHtml.value = ''
      popupRedirectUrl.value = ''
    }
  } catch (e) {
    popupTitle.value = ''
    popupHeadline.value = ''
    popupContentHtml.value = ''
    popupRedirectUrl.value = ''
  }
}

// 添加处理刷新事件的函数
const handleDashboardRefresh = () => {
  // 如果页面可见，刷新所有数据
  if (isPageVisible.value) {
    // console.log('Dashboard 收到刷新事件，正在刷新数据...')
    refreshAllData()
    
    // 重新获取用户信息
    fetchUserInfo()
  }
}

onMounted(() => {
  // 运行诊断
  const diagResult = diagnoseTranslationSystem()
  isPageVisible.value = true

  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }

  // 获取用户信息
  fetchUserInfo()

  // 加载统计数据
  refreshAllData()
  // 加载顶部公告
  loadAnnouncements()
  // 加载业务弹窗内容
  loadBusinessPopup()

  // 检查是否需要自动弹出"更多服务"弹窗
  // 逻辑：首次登录完成设置密码后，或每次新登录时都应该弹窗
  const isFirstLogin = localStorage.getItem('isFirstLogin') === 'true'
  const currentToken = localStorage.getItem('token')
  const lastToken = sessionStorage.getItem('lastDashboardToken')

  // 如果 token 发生变化（说明是新登录），或首次登录完成设置密码后，则弹窗
  if (!isFirstLogin && currentToken && currentToken !== lastToken) {
    // 保存当前 token，用于下次判断
    sessionStorage.setItem('lastDashboardToken', currentToken)

    // 自动弹出"更多服务"弹窗
    // 使用延迟确保页面已完全加载
    nextTick(() => {
      setTimeout(() => {
        showAdPopup.value = true
      }, 500)
    })
  } else if (!lastToken && !isFirstLogin && currentToken) {
    // 页面刷新时，如果没有保存过 token，也要弹窗
    sessionStorage.setItem('lastDashboardToken', currentToken)
    nextTick(() => {
      setTimeout(() => {
        showAdPopup.value = true
      }, 500)
    })
  }

  // 设置定时刷新
  setupRefreshTimer()

  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 初始化滚动条
  nextTick(() => {
    updateScrollbar()
    if (scrollableArea.value) {
      scrollableArea.value.addEventListener('scroll', onContentScroll)
    }
  })

  // 添加窗口大小变化事件监听器
  window.addEventListener('resize', updateScrollbar)

  // 添加监听刷新事件
  window.addEventListener('dashboard-refresh', handleDashboardRefresh)

  // 监听语言切换，重新渲染图表文本
  const handleLanguageChanged = () => {
    // 仅更新图表的多语言文案
    nextTick(() => {
      renderStatsBarChart()
      renderSearchPieChart()
    })
    // 语言变化时刷新公告（若后端未来支持多语言公告则生效）
    loadAnnouncements()
    // 弹窗内容如未来支持多语言，这里也刷新
    loadBusinessPopup()
  }
  document.addEventListener('language-changed', handleLanguageChanged)

  // 在组件卸载时移除语言监听
  onUnmounted(() => {
    document.removeEventListener('language-changed', handleLanguageChanged)
  })
})

// 组件激活时触发刷新
onActivated(() => {
  // 当组件被keep-alive缓存后激活时，刷新数据
  // console.log('Dashboard组件激活，刷新数据...')
  refreshAllData()
  fetchUserInfo()

  // 检查是否需要自动弹出"更多服务"弹窗（处理登出再登录的情况）
  const isFirstLogin = localStorage.getItem('isFirstLogin') === 'true'
  const currentToken = localStorage.getItem('token')
  const lastToken = sessionStorage.getItem('lastDashboardToken')

  // 如果 token 发生变化（说明是新登录），则弹窗
  if (!isFirstLogin && currentToken && currentToken !== lastToken) {
    // 保存当前 token，用于下次判断
    sessionStorage.setItem('lastDashboardToken', currentToken)

    // 自动弹出"更多服务"弹窗
    nextTick(() => {
      setTimeout(() => {
        showAdPopup.value = true
      }, 500)
    })
  }
})

onUnmounted(() => {
  isPageVisible.value = false
  
  // 清除定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
  
  // 移除事件监听器
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  
  if (scrollableArea.value) {
    scrollableArea.value.removeEventListener('scroll', onContentScroll)
  }
  
  window.removeEventListener('resize', updateScrollbar)
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopScroll)
  
  // 移除刷新事件监听
  window.removeEventListener('dashboard-refresh', handleDashboardRefresh)
  
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  if (pieChartInstance) {
    pieChartInstance.dispose()
    pieChartInstance = null
  }
})
</script>

<style scoped>
.dashboard-container {
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  width: 100%;
  position: relative;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex: 1;
  height: 100%;
  min-height: calc(100vh - 60px);
  width: 100%;
  position: relative;
  overflow: hidden;
}

/* 可滚动区域 */
.scrollable-area {
  flex: 1;
  display: flex;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.scrollable-area::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.content {
  flex: 1;
  padding: 20px;
  overflow: visible;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

/* 布局 */
.dashboard-layout {
  display: flex;
  gap: 20px;
  width: 100%;
}

/* 左侧图表区域 */
.charts-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

/* 导出搜索统计卡片 */
.export-search-stats-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(24,144,255,0.06);
  padding: 24px 20px 20px 20px;
  width: 100%;
}

/* 搜索饼图卡片 */
.search-pie-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(24,144,255,0.06);
  padding: 24px 20px 0 20px;
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
}

.stats-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
  letter-spacing: 1px;
  text-align: center;
}

.stats-bar-chart {
  width: 100%;
  height: 340px;
  margin-top: 18px;
}

.search-counts-chart {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 18px;
  flex: 1;
}

.pie-chart {
  width: 100%;
  height: 200px;
}

.chart-legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-bottom: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 10px 10px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.legend-text {
  font-size: 14px;
  color: #666;
}

/* 右侧用户信息区域 */
.user-info-section {
  width: 360px;
  margin-left: 10px;
}

.user-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(24,144,255,0.06);
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.user-card:last-child {
  margin-bottom: 0;
}

/* VIP卡片和顾问卡片样式 */
.vip-card, .advisor-card {
  padding: 15px;
}

/* 用户基本信息 */
.user-profile {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
}

.avatar-container {
  margin-right: 15px;
}

.avatar {
  width: 50px;
  height: 50px;
  background-color: #ff7171;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.user-details {
  flex: 1;
}

.user-id {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.member-tag {
  margin-left: 10px;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: normal;
}

/* 不同会员等级的样式 */
.member-tag.level-0 {
  background-color: #f5f7fa;
  color: #999;
}

.member-tag.level-1 {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.member-tag.level-2 {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.member-tag.level-3 {
  background-color: #fff2e8;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.account-link {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

/* 会员信息 */
.membership-info {
  background-color: #409EFF;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.membership-text {
  font-size: 14px;
  line-height: 1.5;
}

.upgrade-btn {
  background-color: white;
  color: #409EFF;
  border: none;
  height: 32px;
  padding: 0 15px;
}

/* 账户余额 */
.account-balance {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.balance-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.balance-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.balance-amount {
  font-size: 18px;
  font-weight: bold;
}

.recharge-btn {
  background-color: #f5f7fa;
  border: none;
  color: #409EFF;
}

/* 剩余搜索次数 */
.search-remaining {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.remaining-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.remaining-count {
  font-size: 18px;
  font-weight: bold;
}

/* VIP广告横幅 */
.vip-banner {
  width: 100%;
  cursor: pointer;
}

.vip-banner-img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

/* 技术顾问 */
.tech-support {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: center;
  width: 100%;
}

.support-header {
  display: flex;
  align-items: center;
}

.support-text {
  display: flex;
  flex-direction: column;
}

.advisor-icon {
  width: 80px;
  height: 80px;
  margin-right: 12px;
}

.support-title {
  font-size: 16px;
  font-weight: bold;
}

.support-desc {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.qrcode-links-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  width: 90%;
}

.qr-code {
  text-align: center;
  flex-shrink: 0;
}

.qr-code-img {
  width: 130px;
  height: 120px;
}

.support-links {
  display: flex;
  flex-direction: column;
  margin-left: 15px;
  gap: 15px;
}

.link-item {
  font-size: 14px;
  color: #333;
  cursor: pointer;
  padding: 3px 1px;
  border-radius: 4px;
}

/* 自定义滚动条样式 */
.custom-scrollbar {
  position: absolute;
  right: 0;
  top: 0;
  width: 8px;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.05);
  z-index: 1010;
}

.scrollbar-thumb {
  position: absolute;
  width: 8px;
  background-color: rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.scrollbar-thumb:hover {
  background-color: rgba(24, 144, 255, 0.8);
}

/* 适配滚动条布局 */
.main-container {
  position: relative;
}

/* 媒体查询，适应不同屏幕尺寸 */
@media (max-width: 1200px) {
  .dashboard-layout {
    flex-direction: column;
  }
  
  .user-info-section {
    width: 100%;
    margin-left: 0;
    margin-top: 20px;
  }

  .vip-card, .advisor-card {
    margin-top: 0;
  }
}

@media (max-width: 768px) {
  .charts-section {
    flex-direction: column;
  }
}

/* 广告悬浮图标 */
.ad-float-icon {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 60px;
  height: 60px;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1500;
  padding: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.ad-float-icon:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.25);
}

.ad-icon-img {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.ad-icon-text {
  font-size: 10px;
  margin-top: 2px;
  text-align: center;
  line-height: 1.1;
  color: #333;
}

/* 顶部滚动公告样式 */
.marquee-container {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  margin-bottom: 20px;
  background-color: #fff8e6;
  border-radius: 4px;
  border-left: 4px solid #ffb800;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.marquee-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 100%;
  font-size: 18px;
  color: #ff9800;
}

.marquee-content {
  flex: 1;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.marquee-text {
  white-space: nowrap;
  position: absolute;
  height: 100%;
  display: flex;
  align-items: center;
  animation: marquee 20s linear infinite;
  color: #e6a23c;
  font-size: 14px;
}

@keyframes marquee {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@media (max-width: 768px) {
  .marquee-container {
    height: 36px;
  }
  
  .marquee-text {
    font-size: 13px;
  }
}

/* 广告弹窗样式 */
.ad-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.ad-content {
  width: 580px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.ad-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ad-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.ad-close {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  line-height: 1;
}

.ad-body {
  padding: 20px;
  display: flex;
}

.ad-image-container {
  width: 120px;
  margin-right: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.ad-logo {
  width: 100px;
  height: 100px;
  object-fit: contain;
}

.ad-info {
  flex: 1;
}

.ad-info h4 {
  margin: 0 0 10px;
  color: #1890FF;
  font-size: 18px;
}

.ad-info p {
  margin: 0 0 10px;
  color: #333;
  font-size: 14px;
}

.ad-info ul {
  margin: 0;
  padding-left: 20px;
}

.ad-info li {
  margin: 8px 0;
  color: #666;
}

.ad-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.ad-button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
  outline: none;
}

.ad-button.primary {
  background-color: #1890FF;
  color: white;
}

.ad-button.secondary {
  background-color: #f5f5f5;
  color: #666;
}

@media (max-width: 640px) {
  .ad-content {
    width: 90%;
  }
  
  .ad-body {
    flex-direction: column;
  }
  
  .ad-image-container {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }
}

/* 顶部滚动广告样式 */
.top-ad-carousel {
  position: relative;
  width: 100%;
  height: 120px;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.ad-carousel-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
}

.ad-carousel-item {
  flex: 0 0 100%;
  height: 100%;
}

.ad-carousel-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 40px;
  height: 100%;
  color: white;
}

.bg-blue {
  background: linear-gradient(90deg, #1890FF, #0c7ddb);
}

.bg-orange {
  background: linear-gradient(90deg, #FF9F43, #F2732F);
}

.bg-green {
  background: linear-gradient(90deg, #28C76F, #1F9D55);
}

.ad-carousel-text {
  flex: 1;
}

.ad-carousel-text h3 {
  margin: 0 0 10px;
  font-size: 22px;
  font-weight: bold;
}

.ad-carousel-text p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.ad-carousel-action {
  margin-left: 20px;
}

.ad-carousel-btn {
  background-color: white;
  color: #333;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s, transform 0.2s;
}

.ad-carousel-btn:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.ad-carousel-indicators {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.ad-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background-color 0.3s;
}

.ad-indicator.active {
  background-color: white;
}

.ad-carousel-controls {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.ad-carousel-prev,
.ad-carousel-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 30px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  pointer-events: auto;
  transition: background-color 0.3s;
}

.ad-carousel-prev:hover,
.ad-carousel-next:hover {
  background-color: rgba(255, 255, 255, 0.5);
}

.ad-carousel-prev {
  left: 10px;
}

.ad-carousel-next {
  right: 10px;
}

@media (max-width: 768px) {
  .top-ad-carousel {
    height: 150px;
  }
  
  .ad-carousel-content {
    flex-direction: column;
    text-align: center;
    padding: 15px;
  }
  
  .ad-carousel-text h3 {
    font-size: 18px;
  }
  
  .ad-carousel-action {
    margin-left: 0;
    margin-top: 10px;
  }
}

/* 视频教程卡片 */
.video-tutorials-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(24,144,255,0.06);
  padding: 24px 20px 20px 20px;
  width: 100%;
  margin-bottom: 30px;
}

.video-tutorials-grid {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.tutorial-item {
  flex: 1;
  min-width: 280px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.tutorial-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.tutorial-thumbnail {
  position: relative;
  height: 160px;
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  overflow: hidden;
}

.thumbnail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.duration {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-button:after {
  content: '';
  border-left: 15px solid #409EFF;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  margin-left: 5px;
}

.tutorial-title {
  padding: 12px 15px 5px;
  font-weight: bold;
  font-size: 16px;
}

.tutorial-action {
  padding: 0 15px 12px;
  color: #409EFF;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.view-all {
  text-align: center;
  margin-top: 20px;
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

@media (max-width: 992px) {
  .video-tutorials-grid {
    flex-direction: column;
  }
  
  .tutorial-item {
    width: 100%;
  }
}

.icon-container {
  width: 30px;
  height: 30px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 
